#include "../main.h"

void DelQueue(Queue *queue)
{
    while (queue->head != queue->tail)
    {
        DeQueue(queue);
        printf("###\n");
    }
}

void PrintQueue(Queue *queue)
{
    if (IsNull(queue))
    {
        printf("empty queue.\n");
        return;
    }
    Node *curNode = queue->head->next;
    while (curNode)
    {
        if (curNode->next != NULL)
        {
            printf("%s==>", curNode->msg->data);
        }
        else
        {
            printf("%s ", curNode->msg->data);
        }
        curNode = curNode->next;
    }
    //printf("\n");
}

void InitQueue(Queue *queue)
{
    queue->tail = (Node *)malloc(sizeof(Node)); //warning
    queue->tail->msg = (Msgbody *)malloc(sizeof(Msgbody));
    queue->tail->msg->data = "";
    queue->tail->msg->length = 0;
    queue->size = 0;
    queue->head = queue->tail;
    queue->tail->next = NULL;
}
//入队列
void EnQueue(Queue *queue, char *data, int length, int id)
{
    Node *newNode = (Node *)malloc(sizeof(Node)); //warning
    newNode->msg = (Msgbody *)malloc(sizeof(Msgbody));
    newNode->msg->data = malloc(length);
    memcpy(newNode->msg->data, data, length);
    newNode->msg->id = id;
    newNode->msg->length = length;
    newNode->next = NULL;
    queue->tail->next = newNode; //2b 这里漏了。。。导致链表连不上去
    queue->tail = newNode;
    queue->size++;
}
//入队列
void EnQueue_msgBody(Queue *queue, Msgbody *msgbody)
{
    Node *newNode = (Node *)malloc(sizeof(Node)); //warning
    newNode->msg = (Msgbody *)malloc(sizeof(Msgbody));
    newNode->msg->data = malloc(msgbody->length);
    memcpy(newNode->msg->data, msgbody->data, msgbody->length);
    newNode->msg->id = msgbody->id;
    newNode->msg->length = msgbody->length;
    newNode->next = NULL;
    queue->tail->next = newNode; //2b 这里漏了。。。导致链表连不上去
    queue->tail = newNode;
    queue->size++;
}

Msgbody *DeQueue(Queue *queue)
{
    if (IsNull(queue))
    {
        return NULL;
    }
    Msgbody *popValue = queue->head->next->msg;
    Node *popNode = queue->head;
    queue->head = queue->head->next;
    queue->size--;
    // free(popNode->msg->data);
    // popNode->msg->data = NULL;
    // free(popNode->msg);
    // popNode->msg = NULL;
    // free(popNode->next);
    // popNode->next = NULL;
    free(popNode); //warning
    popNode = NULL;

    return popValue;
}
//1 means Null
int IsNull(Queue *queue)
{
    if (queue != NULL)
    {
        if (queue->head != NULL && queue->tail != NULL)
        {
            return (queue->head == queue->tail);
        }
    }
    return 1;
}